/* 腾讯地图JS SDK异步加载器 */
import { TENCENT_MAP_KEY } from './constants'

let loadPromise = null

export function loadTencentMap(customKey) {
  if (typeof window !== 'undefined' && window.qq && window.qq.maps) {
    return Promise.resolve(window.qq)
  }
  if (loadPromise) return loadPromise

  const key = customKey || TENCENT_MAP_KEY
  if (!key) {
    return Promise.reject(new Error('缺少腾讯地图Key，请在环境变量 VUE_APP_TENCENT_MAP_KEY 中配置'))
  }

  loadPromise = new Promise((resolve, reject) => {
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.async = true
    script.defer = true
    script.src = `https://map.qq.com/api/js?v=2.exp&key=${encodeURIComponent(key)}&libraries=place`

    script.onload = () => {
      if (window.qq && window.qq.maps) {
        resolve(window.qq)
      } else {
        reject(new Error('腾讯地图SDK加载失败'))
      }
    }
    script.onerror = () => reject(new Error('腾讯地图SDK脚本加载失败'))

    document.head.appendChild(script)
  })

  return loadPromise
}

export default loadTencentMap 